# -*- coding: utf-8 -*-
__author__ = 'liubei'

import os

# import sae
import web
import db
import db_engine
import time
import sms
import topic
from mongoengine import *
import hashlib
import db_dashboard
import surveyInstanceDB
import datetime
import aes
import az_dateutil
import pytz
import api_statistics

app_root = os.path.dirname(__file__)
templates_root = os.path.join(app_root, 'templates')
render = web.template.render(templates_root)

import simplejson
import random, string

urls = (
    '/', 'helloworld',
    '/survey/admin', 'survey_admin',
    "/static/(.*)", "static_file",
    '/rest/v1/login', 'login',
    '/rest/v1/validatecode', 'validatecode',
    '/rest/v1/validate', 'validate',
    '/rest/v1/validate_invitecode', 'validate_invitecode',
    '/rest/v1/register', 'register',
    '/rest/v1/restpwd', 'restpwd',
    '/rest/v1/caregiverlist', 'caregiverlist',
    '/rest/v1/caregivershare', 'caregivershare',
    '/rest/v1/caregiveradd', 'caregiveradd',
    '/rest/v1/profile/show', 'profileshow',
    '/rest/v1/profile/update', 'profileupdate',
    '/rest/v1/profile/sharedpatientlist', 'sharedpatientlist',
    '/rest/v1/survey', 'survey',
    '/rest/v1/surveyresult', 'surveyresult',
    '/rest/v1/bp', 'bp',
    '/rest/v1/bplist', 'bplist',
    '/rest/v1/bmi', 'bmi',
    '/rest/v1/bmilist', 'bmilist',
    '/rest/v1/cholesterol', 'cholesterol',
    '/rest/v1/cholesterollist', 'cholesterollist',
    '/rest/v1/health/dashboard', 'dashboard',
    '/rest/v1/knowledge/topiclist', 'topiclist',
    '/rest/v1/knowledge/unreadArticleCount', 'unreadArticleCount',
    '/rest/v1/smokelist', 'smokelist',
    '/rest/v1/smoke', 'smoke',
    "/rest/v1/knowledge/topic/(.+)", 'topicdetail',
    "/rest/v1/knowledge/article/(.+)", 'articledetail',
    "/rest/v1/exerciseloglist", 'exerciseloglist',
    "/rest/v1/targetCalorieTotalCount", 'targetCalorieTotalCount',
    "/rest/v1/targetTotalMinute", 'targetTotalMinute',
    "/rest/v1/sporteventlist", 'sporteventlist',
    "/rest/v1/exerciselog", 'exerciselog',
    "/rest/v1/deleteExerice", 'deleteExerice',
    "/rest/v1/knowledge/questionlist/(.+)", 'questionlist',
    "/rest/v1/knowledge/questionanswer", 'questionanswer',
    "/rest/v1/knowledge/record/(.+)", 'recorddetail',
    "/rest/v1/medicineManagement", 'medicineManagement',
    "/rest/v1/medicineCount", 'medicineCount',
    "/rest/v1/medicineList", 'medicineList',
    "/rest/v1/patientadd", 'patientadd',
    # "/rest/v1/testlist", 'listtest',
    "/rest/v1/logout", 'logout',


    "/rest/v1/userList", 'userList',
    "/rest/v1/article", 'article',
    "/rest/v1/question", 'question',
    "/rest/v1/topic", 't',

    '/rest/vadmin/login', 'admin_login',
    '/rest/vadmin/survey/schedule', 'admin_survey_schedule',
    '/rest/vadmin/survey/scheduleCheck', 'admin_survey_schedule_check',
    '/rest/vadmin/removeUser', 'admin_remove_user',
)

class helloworld:
    def GET(self):
        web.header('content-type', 'text/html')
        return """
    <li>/rest/v1/login</li>
    <li>/rest/v1/validatecode</li>
    <li>/rest/v1/validate</li>
    <li>/rest/v1/validate_invitecode</li>
    <li>/rest/v1/register</li>
    <li>/rest/v1/restpwd</li>
    <li>/rest/v1/caregiverlist</li>
    <li>/rest/v1/caregivershare</li>
    <li>/rest/v1/caregiveradd</li>
    <li>/rest/v1/profile/show</li>
    <li>/rest/v1/profile/update</li>
    <li>/rest/v1/profile/sharedpatientlist</li>
    <li>/rest/v1/survey</li>
    <li>/rest/v1/bp</li>
    <li>/rest/v1/bplist</li>
    <li>/rest/v1/bmi</li>
    <li>/rest/v1/bmilist</li>
    <li>/rest/v1/health/dashboard</li>

    <li><a href=http://git.oschina.net/beiliubei/api_define/blob/master/az-server_api%E5%AE%9A%E4%B9%89.md>api 文档地址</a><li>
    <li><a href=/survey/admin>问卷调查后台<li></a>
        """


class survey_admin:
    def GET(self):
        web.header('content-type', 'text/html')
        return web.seeother('/static/login.html')


class static_file:
    def __init__(self):
        pass
    def GET(self, path):
        print "in static_file"
        return web.seeother("static/" + path)


def random_str(randomlength=16):
    a = list(string.ascii_letters)
    random.shuffle(a)
    return ''.join(a[:randomlength])


class validatecode:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        userPhone = jsonDic['userPhone']
        type = jsonDic['type']
        print jsonDic
        dic={}
        dic['validateCode'] = ''.join(random.sample(['1', '2', '3', '4', '5', '6', '7', '8', '9'], 6))
        #2 重置密码
        if type == 2:
            user = db.query(userPhone)
            if user == None:
                raise web.NotFound("")
            text = '【e-Help China】正在找回密码，您的验证码是%s'%(dic['validateCode'])
        #1 注册
        elif type == 1:
            user = db.query(userPhone)
            if user != None:
                raise web.conflict
            text = '【e-Help China】感谢你注册这款智能软件，您的验证码是%s'%(dic['validateCode'])
        dic['userPhone'] = userPhone
        validatecodes = db_engine.queryValidateCode(userPhone)
        if validatecodes.count() == 0:
            db_engine.createValidateCode(dic)
        else:
            db_engine.updateValidate(dic)
        print sms.send_sms(text, userPhone)
        web.header('content-type', 'application/json')
        return simplejson.dumps({})


class restpwd:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        userPhone = jsonDic['userPhone']
        userPwd = jsonDic['userPwd']
        user = db.query(userPhone)
        if user == None:
            raise web.NotFound("")
        user['userPwd'] = hashlib.md5(userPwd).hexdigest().upper()
        db.updateUserPwd(user)
        web.header('content-type', 'application/json')
        return simplejson.dumps({})


class login:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        userPhone = jsonDic['userPhone']
        userPwd = jsonDic['userPwd']
        user = db.query(userPhone)
        if user == None:
            raise web.NotFound("")
        elif user['userPwd'] != hashlib.md5(userPwd).hexdigest().upper():
            raise web.unauthorized
        web.header('content-type', 'application/json')
        accessToken = random_str()
        db.createToken({'accessToken': accessToken, 'userPhone': userPhone})
        isSmoke = 0
        if user.has_key('isSmoke') and user['isSmoke'] == 1:
            isSmoke = 1
        hasHighBp = 0
        if user.has_key('hasHighBp') and user['hasHighBp'] == 1:
            hasHighBp = 1
        #
        # medicineDic = db_engine.queryMedicineListByParam(userPhone, 0, 1, 0)
        # if len(medicineDic['medicines'])>0:
        #     remainingMedicine = medicineDic['medicines'][0]['remainingMedicine']
        # #
        remainingMedicine = -1
        if user.has_key('remainingMedicine'):
            remainingMedicine = user['remainingMedicine']

        surveySchedule = surveyInstanceDB.querySurveySchedule(userPhone)
        firstDoneSurveyTime = surveySchedule.firstDone
        aes_cipher = aes.AESCipher(aes.aes_key)
        lastDoneSurvey = aes_cipher.decrypt(surveySchedule.lastSurvey)
        remainingMedicine = aes_cipher.decrypt(remainingMedicine)
        setApiVersion()
        userBirthday = aes_cipher.decrypt(user['userBirthday'])
        userGender = aes_cipher.decrypt(user['userGender'])
        return simplejson.dumps({'userBirthday': userBirthday, 'createDate': user['createDate'],
                                 'accessToken': accessToken, 'uid': str(user['_id']), 'userPhone': userPhone,
                                 'nickName': user['nickName'], 'userType': user['userType'], 'userGender': userGender,
                                 'isSmoke': isSmoke, 'patientCode': user['patientCode'],
                                 'hasHighBp':hasHighBp, 'userHeight': user['userHeight'],
                                 'remainingMedicine': remainingMedicine, 'firstDoneSurveyTime': firstDoneSurveyTime,
                                 'lastDoneSurvey': lastDoneSurvey})


class validate:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        userPhone = jsonDic['userPhone']
        validateCode = jsonDic['validateCode']
        #temp mark
        if validateCode == "000000":
            web.header('content-type', 'application/json')
            return simplejson.dumps({})
        else:
            validatecodes = db_engine.queryValidateCode(userPhone)
            if validatecodes.count() == 0:
                raise web.NotFound("")
            if validateCode != validatecodes[0].validateCode:
                raise web.NotFound("")
            web.header('content-type', 'application/json')
            return simplejson.dumps({})


class validate_invitecode:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        userPhone = jsonDic['userPhone']
        inviteCode = jsonDic['inviteCode']
        #TODO: hard code inviteCode
        if inviteCode != '111111':
            raise web.NotFound("")
        web.header('content-type', 'application/json')
        return simplejson.dumps({})


class register:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        userPhone = jsonDic['userPhone']
        userType = jsonDic['userType']
        nickName = jsonDic['nickName']
        userBirthday = jsonDic['userBirthday']
        userHeight = jsonDic['userHeight']
        userGender = jsonDic['userGender']
        patientCode = jsonDic['patientCode']
        isSmoke = int(jsonDic['isSmoke'])
        if not userType == 2:
            #验证唯一性
            userP = db_engine.queryUserByPatientCode(patientCode)
            if not userP == None and userP.userPhone != userPhone:
                raise web.conflict
            #停止E13用户的注册,招募结束
            if 'E13' in patientCode:
                raise web.conflict
        hasHighBp = 0
        if jsonDic.has_key('hasHighBp'):
            hasHighBp = int(jsonDic['hasHighBp'])
        userPwd = jsonDic['userPwd']
        userPwd = hashlib.md5(userPwd).hexdigest().upper()
        jsonDic['userPwd'] = userPwd
        jsonDic['createDate'] = int(time.time())
        jsonDic['remainingMedicine'] = -1
        aes_cipher = aes.AESCipher(aes.aes_key)
        jsonDic['userBirthday'] = aes_cipher.encrypt(userBirthday)
        jsonDic['userGender'] = aes_cipher.encrypt(userGender)
        db.createUser(jsonDic)
        web.header('content-type', 'application/json')
        #返回数据
        user = db.query(userPhone)
        dic = {}
        dic['userPhone'] = user['userPhone']
        dic['uid'] = str(user['_id'])
        dic['nickName'] = user['nickName']
        dic['userType'] = user['userType']
        dic['userGender'] = userGender
        dic['isSmoke'] = user['isSmoke']
        dic['patientCode'] = user['patientCode']
        dic['accessToken'] = random_str()
        dic['hasHighBp'] = user['hasHighBp']
        dic['createDate'] = user['createDate']
        dic['remainingMedicine'] = -1
        dic['userBirthday'] = userBirthday
        return simplejson.dumps(dic)


class caregiverlist:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        print accessToken
        web.header('content-type', 'application/json')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized

        caregiverList = []
        caregivers = db_engine.queryCaregiversByCaredUserPhone(dbToken['userPhone'])
        for caregiver in caregivers:
            user = db_engine.queryUser(caregiver.userPhone)
            caregiverDic = {}
            if user == None:
                caregiverDic['validate'] = 0
                caregiverDic['nickName'] = caregiver.userPhone
            else:
                caregiverDic['nickName'] = user.nickName
                if caregiver.inviteCode == 0:
                    caregiverDic['validate'] = 1
                else:
                    caregiverDic['validate'] = 0
            caregiverDic['uid'] = str(caregiver.id)
            caregiverDic['createDate'] = caregiver.createDate
            caregiverDic['shared'] = caregiver.shared
            caregiverDic['userPhone'] = caregiver.userPhone
            caregiverList.append(caregiverDic)
        return simplejson.dumps(caregiverList)


class caregivershare:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        uid = jsonDic['uid']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        db_engine.updateCaregiverByUid(uid, 1)
        print 'add share'
        web.header('content-type', 'application/json')
        return simplejson.dumps({})

    def DELETE(self):
        i = web.data()
        jsonDic = {}
        if i == '':
            print 'empty i'
            i = web.input()
            jsonDic['accessToken'] = i.get("accessToken")
            if i.has_key('uid'):
                jsonDic['uid'] = i.get('uid')
        else:
            jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        uid = jsonDic['uid']
        print 'delete share'
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        db_engine.updateCaregiverByUid(uid, 0)
        web.header('content-type', 'application/json')
        return simplejson.dumps({})


class caregiveradd:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        userPhone = jsonDic['userPhone']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        dbUser = db_engine.queryUser(userPhone)
        if not dbUser == None:
            if dbUser.userType == '1' or dbToken['userPhone'] == userPhone:
                #用户手机号已经被注册成病人
                raise web.conflict

        dic = {}
        dic['caredUserPhone'] = dbToken['userPhone']
        dic['nickName'] = userPhone
        dic['userPhone'] = userPhone
        dic['inviteCode'] = ''.join(random.sample(['1', '2', '3', '4', '5', '6', '7', '8', '9'], 6))
        dic['inviteCode'] = singleInviteCode(dic['inviteCode'])
        #send ems dic['inviteCode']
        # text = "【血脂达人】您有一条新的邀请码%s" %(dic['inviteCode'])
        text = "【e-Help China】您的验证码是%s" %(dic['inviteCode'])
        print text
        print sms.send_sms(text, userPhone)
        if db_engine.queryCaregiverByPhone(dic['caredUserPhone'], userPhone).count() > 0:
            db_engine.updateCaregiver(dic)
        else:
            db_engine.createCaregiver(dic)
        web.header('content-type', 'application/json')
        caregiver = db_engine.queryCaregiverByPhone(dbToken['userPhone'], userPhone)[0]
        responsDic = {}
        responsDic['uid'] = str(caregiver.id)
        responsDic['createDate'] = caregiver.createDate
        responsDic['shared'] = caregiver.shared
        responsDic['userPhone'] = caregiver.userPhone
        responsDic['nickName'] = caregiver.nickName
        user = db_engine.queryUser(caregiver.userPhone)
        if user == None:
            responsDic['validate'] = 0
            responsDic['nickName'] = caregiver.userPhone
        else:
            responsDic['nickName'] = caregiver.nickName
            if caregiver.inviteCode == 0:
                responsDic['validate'] = 1
            else:
                responsDic['validate'] = 0
        return simplejson.dumps(responsDic)


def singleInviteCode(code):
    #验证邀请码是否已经被占用
    caregivers = db_engine.queryCaregivers()
    for caregiver in caregivers:
        if caregiver.inviteCode == code:
            print 'invitecode exist regenter'
            code = ''.join(random.sample(['1', '2', '3', '4', '5', '6', '7', '8', '9'], 6))
            singleInviteCode(code)
            break
    return code


class profileshow:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        print accessToken
        web.header('content-type', 'application/json')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        if i.has_key('uid'):
            user = db_engine.queryUserById(i.get('uid'))
        else:
            user = db_engine.queryUser(dbToken['userPhone'])
            if user == None:
                raise web.NotFound("")
        userDic = {}
        userDic['userPhone'] = user.userPhone
        userDic['nickName'] = user.nickName
        aes_cipher = aes.AESCipher(aes.aes_key)
        userBirthday = aes_cipher.decrypt(user.userBirthday)
        userDic['userBirthday'] = userBirthday
        userDic['userHeight'] = user.userHeight
        userGender = aes_cipher.decrypt(user.userGender)
        userDic['userGender'] = userGender
        userDic['userType'] = user.userType
        userDic['uid'] = str(user.id)
        userDic['isSmoke'] = user.isSmoke
        userDic['patientCode'] = user.patientCode
        userDic['createDate'] = user.createDate
        if user.hasHighBp == None:
            userDic['hasHighBp'] = 0
        else:
            userDic['hasHighBp'] = user.hasHighBp
            #
        remainingMedicine = user.remainingMedicine
        surveySchedule = surveyInstanceDB.querySurveySchedule(dbToken['userPhone'])
        firstDoneSurveyTime = surveySchedule.firstDone
        lastDoneSurvey = aes_cipher.decrypt(surveySchedule.lastSurvey)
        userDic['remainingMedicine'] = aes_cipher.decrypt(remainingMedicine)
        userDic['firstDoneSurveyTime'] = firstDoneSurveyTime
        userDic['lastDoneSurvey'] = lastDoneSurvey
        return simplejson.dumps(userDic)


class profileupdate:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        nickName = jsonDic['nickName']
        userBirthday = jsonDic['userBirthday']
        userHeight = jsonDic['userHeight']
        userGender = jsonDic['userGender']
        accessToken = jsonDic['accessToken']
        isSmoke = int(jsonDic['isSmoke'])
        patientCode = jsonDic['patientCode']

        dic = {}
        if jsonDic.has_key('remainingMedicine'):
            remainingMedicine = jsonDic['remainingMedicine']
        else:
            remainingMedicine = 0
        hasHighBp = 0
        if jsonDic.has_key('hasHighBp'):
            hasHighBp = int(jsonDic['hasHighBp'])
        web.header('content-type', 'application/json')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        user = db_engine.queryUser(dbToken['userPhone'])
        if not user.userType == 2:
            #验证唯一性
            userP = db_engine.queryUserByPatientCode(patientCode)
            if not userP == None and userP.userPhone != dbToken['userPhone']:
                raise web.conflict
        dic['userPhone'] = dbToken['userPhone']
        dic['nickName'] = nickName
        dic['userHeight'] = userHeight
        dic['isSmoke'] = isSmoke
        dic['patientCode'] = patientCode
        dic['hasHighBp'] = hasHighBp
        aes_cipher = aes.AESCipher(aes.aes_key)
        dic['userBirthday'] = aes_cipher.encrypt(userBirthday)
        dic['userGender'] = aes_cipher.encrypt(userGender)
        dic['remainingMedicine'] = aes_cipher.encrypt(remainingMedicine)
        db_engine.updateUser(dic)
        dic['uid'] = str(user.id)
        dic['userType'] = user.userType
        dic['createDate'] = user.createDate
        dic['userBirthday'] = userBirthday
        dic['userGender'] = userGender
        dic['remainingMedicine'] = remainingMedicine
        return simplejson.dumps(dic)


class sharedpatientlist:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        print accessToken
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        caregivers = db_engine.queryCaregiverSharedByPhone(dbToken['userPhone'])
        userList = []
        iosWeekDay = datetime.datetime.today().isoweekday()
        monday = datetime.datetime.today()-datetime.timedelta(iosWeekDay-1)
        mondayTime = int(time.mktime(monday.replace(monday.year, monday.month, monday.day, 0, 0, 0).timetuple()))
        aes_cipher = aes.AESCipher(aes.aes_key)
        for caregiver in caregivers:
            userDic = {}
            user = db_engine.queryUser(caregiver.caredUserPhone)
            userDic['uid'] = str(user.id)
            userDic['nickName'] = user.nickName
            bmiDic = db.queryBmiList(user.userPhone, 0, 1)
            if len(bmiDic['bmis']) == 0:
                userDic['bmiIndex'] = 0.0
            else:
                userDic['bmiIndex'] = bmiDic['bmis'][0]['bmiIndex']
            medicineDic = db_engine.queryMedicineListByParam(user.userPhone, 0, 1, 0)
            if len(medicineDic['medicines']) == 0:
                userDic['takingDays'] = 0
            else:
                userDic['takingDays'] = aes_cipher.decrypt(max(medicineDic['medicines'][0]['remainingMedicine'], 0))

            exericeLogDic = db.queryExerciseloglist(user.userPhone, 0, 7)
            if len(exericeLogDic['exericelogs']) == 0:
                userDic['consumeHeatCount'] = 0.0
                userDic['totalMin'] = 0
            else:
                totalMin = 0
                for log in exericeLogDic['exericelogs']:
                    print mondayTime
                    print  log['createDate']
                    if log['createDate'] >= mondayTime:
                        totalMin += log['totalMinute']

                userDic['consumeHeatCount'] = 0
                userDic['totalMin'] = totalMin
            userList.append(userDic)
        web.header('content-type', 'application/json')
        return simplejson.dumps(userList)


class survey:
    def GET(self):
        web.header('content-type', 'application/json')
        i = web.input()
        accessToken = i.get('accessToken')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        userPhone = dbToken['userPhone']
        surverySchedule = surveyInstanceDB.querySurveySchedule(userPhone)
        surveyDic = {}
        surveyList = []
        aes_cipher = aes.AESCipher(aes.aes_key)
        surveyDb = db_engine.querySurveyByName(aes_cipher.decrypt(surverySchedule.currentSurvey))
        if surveyDb == None:
            surveyDic['lastSurvey'] = aes_cipher.decrypt(surverySchedule.lastSurvey)
            surveyDic['lastDone'] = surverySchedule.lastDone
            surveyDic['uid'] = ''
            surveyDic['name'] = ''
            surveyDic['des'] = ''
            surveyDic['firstNode'] = ''
            surveyDic['surveies'] = []
        else:
            surveyDic['uid'] = str(surveyDb.id)
            surveyDic['name'] = surveyDb.name
            surveyDic['des'] = surveyDb.des
            surveyDic['firstNode'] = surveyDb.firstNode
            surveyDic['lastSurvey'] = aes_cipher.decrypt(surverySchedule.lastSurvey)
            surveyDic['lastDone'] = surverySchedule.lastDone
            for s in surveyDb.surveies:
                sDic = {}
                sDic['uid'] = str(s.id)
                sDic['content'] = s.content
                sDic['choices'] = s.choices
                sDic['type'] = s.type
                sDic['nextIds'] = s.nextIds
                surveyList.append(sDic)
            surveyDic['surveies'] = surveyList
        #记录用户使用了app
        api_statistics.logHome(userPhone)
        return simplejson.dumps(surveyDic)


class bp:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        if jsonDic.has_key('bps'):
            models = jsonDic['bps']
            modelList = []
            for modelDic in models:
                modelList.append(self.createOrUpdate(modelDic, dbToken))
            return simplejson.dumps(modelList)
        else:
            return simplejson.dumps(self.createOrUpdate(jsonDic, dbToken))

    def createOrUpdate(self, jsonDic, dbToken):
        if not jsonDic.has_key('createDate'):
            jsonDic['createDate'] = int(time.time())
        bpHighIndex = jsonDic['bpHighIndex']
        bpLowIndex = jsonDic['bpLowIndex']
        dic = {}
        aes_cipher = aes.AESCipher(aes.aes_key)
        dic['bpHighIndex'] = aes_cipher.encrypt(bpHighIndex)
        dic['bpLowIndex'] = aes_cipher.encrypt(bpLowIndex)
        dic['createDate'] = jsonDic['createDate']
        dic['userPhone'] = dbToken['userPhone']
        uid = db.updateBp(dic)
        dic['uid'] = str(uid)
        dic.pop('userPhone')
        dic['bpHighIndex'] = bpHighIndex
        dic['bpLowIndex'] = bpLowIndex
        if dic.has_key('_id'):
            dic.pop('_id')
        return dic

    def DELETE(self):
        i = web.data()
        jsonDic = {}
        if i == '':
            print 'empty i'
            i = web.input()
            jsonDic['accessToken'] = i.get("accessToken")
            if i.has_key('uid'):
                jsonDic['uid'] = i.get('uid')
            if i.has_key('uids'):
                jsonDic['uids'] = i.get('uids')
        else:
            jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        if jsonDic.has_key('uid') or jsonDic.has_key('uids'):
            if jsonDic.has_key('uid'):
                uid = jsonDic['uid']
                db.deleteBp(uid)
            elif jsonDic.has_key('uids'):
                uids = jsonDic['uids'].split(',')
                for uid in uids:
                    db.deleteBp(uid)
        else:
            db.deleteAllBpByPhone(dbToken['userPhone'])
        return simplejson.dumps({})


class bplist:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        userPhone = dbToken['userPhone']
        if i.has_key('profileId') and len(i.get('profileId')) > 0:
            profileId = i.get('profileId')
            user = db_engine.queryUserById(profileId)
            userPhone = str(user.userPhone)
        page = 0
        pageSize = 10
        if i.has_key('page'):
            if len(i.get('page')) > 0:
                page = int(i.get('page'))
        if i.has_key('pageSize'):
            if len(i.get('pageSize')) > 0:
                pageSize = int(i.get('pageSize'))
        bpDic = db.queryBpList(userPhone, page, pageSize)
        return simplejson.dumps(bpDic)


class bmi:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        if jsonDic.has_key('bmis'):
            models = jsonDic['bmis']
            modelList = []
            for modelDic in models:
                modelList.append(self.createOrUpdate(modelDic, dbToken))
            return simplejson.dumps(modelList)
        else:
            return simplejson.dumps(self.createOrUpdate(jsonDic, dbToken))

    def createOrUpdate(self, jsonDic, dbToken):
        height = jsonDic['height']
        weight = jsonDic['weight']
        targetWeight = jsonDic['targetWeight']
        if not jsonDic.has_key('createDate'):
            jsonDic['createDate'] = int(time.time())
        dic = {}
        dic['height'] = height
        dic['weight'] = weight
        dic['targetWeight'] = targetWeight
        dic['bmiIndex'] = round(float(weight)/(float(height)/100 * float(height)/100), 2)
        dic['targetBmiIndex'] = round(targetWeight/(float(height)/100 * float(height)/100), 2)
        dic['createDate'] = jsonDic['createDate']
        dic['userPhone'] = dbToken['userPhone']
        uid = db.updateBmi(dic)
        dic['uid'] = str(uid)
        dic.pop('userPhone')
        if dic.has_key('_id'):
            dic.pop('_id')
        return dic

    def DELETE(self):
        i = web.data()
        jsonDic = {}
        if i == '':
            print 'empty i'
            i = web.input()
            jsonDic['accessToken'] = i.get("accessToken")
            if i.has_key('uid'):
                jsonDic['uid'] = i.get('uid')
            if i.has_key('uids'):
                jsonDic['uids'] = i.get('uids')
        else:
            jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        if jsonDic.has_key('uid') or jsonDic.has_key('uids'):
            if jsonDic.has_key('uid'):
                uid = jsonDic['uid']
                db.deleteBmi(uid)
            elif jsonDic.has_key('uids'):
                uids = jsonDic['uids'].split(',')
                for uid in uids:
                    db.deleteBmi(uid)
        else:
            db.deleteAllBmiByPhone(dbToken['userPhone'])
        return simplejson.dumps({})


class bmilist:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        userPhone = dbToken['userPhone']
        if i.has_key('profileId') and len(i.get('profileId')) > 0 and (not i.get('profileId') == '(null)'):
            profileId = i.get('profileId')
            user = db_engine.queryUserById(profileId)
            userPhone = str(user.userPhone)
        page = 0
        pageSize = 10
        if i.has_key('page'):
            if len(i.get('page')) > 0:
                page = int(i.get('page'))
        if i.has_key('pageSize'):
            if len(i.get('pageSize')) > 0:
                pageSize = int(i.get('pageSize'))
        bpDic = db.queryBmiList(userPhone, page, pageSize)
        return simplejson.dumps(bpDic)


#
class cholesterol:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        if jsonDic.has_key('cholesterols'):
            cholesterols = jsonDic['cholesterols']
            cholesterollist = []
            for cholesterolDic in cholesterols:
                cholesterollist.append(self.createOrUpdate(cholesterolDic, dbToken))
            return simplejson.dumps(cholesterollist)
        else:
            return simplejson.dumps(self.createOrUpdate(jsonDic, dbToken))

    def createOrUpdate(self, jsonDic, dbToken):
        low = jsonDic['low']
        high = jsonDic['high']
        tg = jsonDic['tg']
        if not jsonDic.has_key('createDate'):
            jsonDic['createDate'] = int(time.time())
        if not jsonDic.has_key('tc'):
            tc = 0.0
        else:
            tc = jsonDic['tc']
        aes_cipher = aes.AESCipher(aes.aes_key)
        dic = {}
        dic['low'] = aes_cipher.encrypt(low)
        dic['high'] = aes_cipher.encrypt(high)
        dic['tg'] = aes_cipher.encrypt(tg)
        dic['tc'] = aes_cipher.encrypt(tc)
        dic['createDate'] = jsonDic['createDate']
        dic['userPhone'] = dbToken['userPhone']
        uid = db.updateCholesterol_fix(dic)
        dic['uid'] = str(uid)
        dic.pop('userPhone')
        if dic.has_key('_id'):
            dic.pop('_id')
        dic['low'] = low
        dic['high'] = high
        dic['tg'] = tg
        dic['tc'] = tc
        return dic

    def DELETE(self):
        i = web.data()
        jsonDic = {}
        if i == '':
            print 'empty i'
            i = web.input()
            jsonDic['accessToken'] = i.get("accessToken")
            if i.has_key('uid'):
                jsonDic['uid'] = i.get('uid')
            if i.has_key('uids'):
                jsonDic['uids'] = i.get('uids')
        else:
            jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        if jsonDic.has_key('uid') or jsonDic.has_key('uids'):
            if jsonDic.has_key('uid'):
                uid = jsonDic['uid']
                db.deleteCholesterol(uid)
            elif jsonDic.has_key('uids'):
                uids = jsonDic['uids'].split(',')
                for uid in uids:
                    db.deleteCholesterol(uid)
        else:
            db.deleteAllCholesterolByPhone(dbToken['userPhone'])
        return simplejson.dumps({})


class cholesterollist:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        userPhone = dbToken['userPhone']
        if i.has_key('profileId') and len(i.get('profileId')) > 0 and (not i.get('profileId') == '(null)'):
            profileId = i.get('profileId')
            user = db_engine.queryUserById(profileId)
            userPhone = str(user.userPhone)
        page = 0
        pageSize = 10
        if i.has_key('page'):
            if len(i.get('page')) > 0:
                page = int(i.get('page'))
        if i.has_key('pageSize'):
            if len(i.get('pageSize')) > 0:
                pageSize = int(i.get('pageSize'))
        bpDic = db.queryCholesterolList(userPhone, page, pageSize)
        return simplejson.dumps(bpDic)


class dashboard:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        userPhone = dbToken['userPhone']
        if i.has_key('profileId') and len(i.get('profileId')) > 0 and (not i.get('profileId') == '(null)'):
            profileId = i.get('profileId')
            user = db_engine.queryUserById(profileId)
            userPhone = str(user.userPhone)
        else:
            api_statistics.logHome(userPhone)
        pageSize = 10
        bmiDic = db.queryBmiList(userPhone, 0, pageSize)
        bpDic = db.queryBpList(userPhone, 0, pageSize)
        cholesterolDic = db.queryCholesterolList(userPhone, 0, pageSize)
        exericeLogDic = db.queryExerciseloglist(userPhone, -1, pageSize)
        aes_cipher = aes.AESCipher(aes.aes_key)

        now = int(time.time())
        tz = pytz.timezone(pytz.country_timezones('cn')[0])
        thisDate = datetime.datetime.fromtimestamp(now, tz)
        now = int(az_dateutil.date2timestamp(thisDate.replace(thisDate.year, thisDate.month, thisDate.day, 0, 0, 0))) + 16*60*60

        medicineList = db_dashboard.queryMedicinelistBetweenDays(now, now - 37*24*60*60, userPhone)
        medicineL = []
        remainingMedicine = db_engine.queryUser(userPhone).remainingMedicine
        for day in range(1, 37, 1):
            medicineDic = {}
            find = False
            cTimeLong = now - day*24*60*60
            for medicine in medicineList:
                cTime = datetime.datetime.fromtimestamp(float(cTimeLong), tz).strftime("%Y-%m-%d")
                nTime = datetime.datetime.fromtimestamp(float(medicine.createDate), tz).strftime("%Y-%m-%d")
                if cTime == nTime:
                    find = True
                    medicineDic['uid'] = str(medicine.id)
                    medicineDic['createDate'] = medicine.createDate
                    medicineDic['done'] = aes_cipher.decrypt(medicine.done)
            if not find:
                medicineDic['createDate'] = cTimeLong
                medicineDic['done'] = 0
            medicineDic['remainingMedicine'] = aes_cipher.decrypt(remainingMedicine)
            medicineL.append(medicineDic)

        resultDic = {}
        resultDic['healthIndex'] = calHealthIndex(userPhone)
        resultDic['bmis'] = bmiDic['bmis']
        resultDic['bps'] = bpDic['bps']
        resultDic['cholesterols'] = cholesterolDic['cholesterols']
        resultDic['exericelogs'] = exericeLogDic['exericelogs']
        resultDic['medicines'] = medicineL
        return simplejson.dumps(resultDic)


def calHealthIndex(userPhone):
    now = int(time.time())
    #Physical Activity
    exerciseloglist = db_dashboard.queryExericeLogBetweenDays(now, now - 7*24*60*60, userPhone)
    exericeScore = 0.0
    min = 0
    for exerciselog in exerciseloglist:
        exerices = db_dashboard.queryExericeByLogId(str(exerciselog.id))
        for exerice in exerices:
            min = min + exerice.min
    if min >= 150:
        exericeScore = 100
    elif min == 0:
        exericeScore = 0
    else:
        exericeScore = min/150.0*100.0
    #Medicine
    medicineList = db_dashboard.queryMedicinelistBetweenDays(now, now - 7*24*60*60, userPhone)
    medicineScore = 100.0
    days = (0, 1, 2, 3, 4, 5, 6)
    medicineStatus = []
    for day in days:
        find = False
        cTimeLong = now - day*24*60*60
        for medicine in medicineList:
            cTime = time.strftime('%Y-%m-%d', time.localtime(cTimeLong))
            nTime = time.strftime('%Y-%m-%d', time.localtime(medicine.createDate))
            if cTime == nTime:
                find = True
                medicineStatus.append(medicine.done)
        if not find:
            medicineStatus.append(0)
    print medicineStatus
    scoreList = []
    index = 0
    for status in medicineStatus:
        if status == 0:
            scoreList.append(status)
            if index + 1 == len(medicineStatus):
                if len(scoreList) == 1:
                    medicineScore -= 10
                elif len(scoreList) == 2:
                    medicineScore -= 40
                elif len(scoreList) == 3:
                    medicineScore -= 60
                scoreList = []
        elif status == 1:
            if len(scoreList) == 1:
                medicineScore -= 10
            elif len(scoreList) == 2:
                medicineScore -= 40
            elif len(scoreList) == 3:
                medicineScore -= 60
            scoreList = []
        index += 1
    print medicineScore

    #bmi
    bmiScore = 0.0
    bmilist = db_dashboard.queryBmiBetweenDays(now, now - 4*7*24*60*60, userPhone)
    if len(bmilist):
        fBmi = bmilist[0]
        lBmi = bmilist[len(bmilist) - 1]
        weight_lose = fBmi.weight - lBmi.weight
        print fBmi.createDate
        print lBmi.createDate
        print weight_lose
        if fBmi.bmiIndex < 25 or weight_lose < -0.75:
            bmiScore = 100
        elif -0.75 < weight_lose < -0.5:
            bmiScore = 90
        elif fBmi.bmiIndex > 35 or -0.5 < weight_lose < 0.5:
            bmiScore = 0
        print bmiScore

    #smoke
    smokeScore = 100.0
    # smokelist = db_dashboard.querySmokeBetweenDays(now, now - 1*24*60*60, userPhone)
    # if len(smokelist) > 0:
    #     smoke = smokelist[0]
    #     if smoke.count >= 5:
    #         smokeScore = 0.0
    #     elif smoke < 5 and smoke > 0:
    #         smokeScore = 30
    user = db_engine.queryUser(userPhone)
    if user.isSmoke == 1:
        smokeScore = 0.0

    return exericeScore*0.2 + medicineScore*0.4 + smokeScore*0.2 + bmiScore*0.2


class topiclist:
    def GET(self):
        i = web.input()
        page = 0
        pageSize = 10
        if i.has_key('page'):
            if len(i.get('page')) > 0:
                page = int(i.get('page'))
        if i.has_key('pageSize'):
            if len(i.get('pageSize')) > 0:
                pageSize = int(i.get('pageSize'))
        userPhone = None
        if i.has_key('accessToken'):
            accessToken = i.get('accessToken')
            if len(accessToken)>0:
                dbToken = db.queryUserByToken(accessToken)
                if dbToken == None:
                    raise web.unauthorized
                else:
                    userPhone = dbToken['userPhone']
        topicDic = db.queryTopicList(userPhone, page, pageSize)
        setApiVersion()
        return simplejson.dumps(topicDic)


class topicdetail:
    def GET(self, uid):
        i = web.input()
        userPhone = None
        if i.has_key('accessToken'):
            accessToken = i.get('accessToken')
            if len(accessToken)>0:
                dbToken = db.queryUserByToken(accessToken)
                if dbToken == None:
                    raise web.unauthorized
                else:
                    userPhone = dbToken['userPhone']
        setApiVersion()
        # save log
        api_statistics.logLongMessageCatalog(userPhone, uid)
        return simplejson.dumps(db.queryArticleListByTopicId(uid, userPhone))


class articledetail:
    def GET(self, uid):
        setApiVersion()
        i = web.input()
        userPhone = None
        if i.has_key('accessToken'):
            accessToken = i.get('accessToken')
            if len(accessToken)>0:
                dbToken = db.queryUserByToken(accessToken)
                if dbToken == None:
                    raise web.unauthorized
                else:
                    userPhone = dbToken['userPhone']
        return simplejson.dumps(db.queryArticle(uid, userPhone))


class smokelist:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        userPhone = dbToken['userPhone']
        if i.has_key('profileId') and len(i.get('profileId')) > 0 and (not i.get('profileId') == '(null)'):
            profileId = i.get('profileId')
            user = db_engine.queryUserById(profileId)
            userPhone = str(user.userPhone)
        page = 0
        pageSize = 10
        if i.has_key('page'):
            if len(i.get('page')) > 0:
                page = int(i.get('page'))
        if i.has_key('pageSize'):
            if len(i.get('pageSize')) > 0:
                pageSize = int(i.get('pageSize'))
        return simplejson.dumps(db.querySmokeList(userPhone, page, pageSize))


class smoke:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        if jsonDic.has_key('smokes'):
            models = jsonDic['smokes']
            modelList = []
            for modelDic in models:
                modelList.append(self.createOrUpdate(modelDic, dbToken))
            return simplejson.dumps(modelList)
        else:
            return simplejson.dumps(self.createOrUpdate(jsonDic, dbToken))


    def createOrUpdate(self, jsonDic, dbToken):
        createDate = jsonDic['createDate']
        count = jsonDic['count']
        dic = {}
        dic['createDate'] = createDate
        dic['count'] = count
        dic['userPhone'] = dbToken['userPhone']
        uid = db.updateSmoke(dic)
        dic['uid'] = str(uid)
        dic.pop('userPhone')
        if dic.has_key('_id'):
            dic.pop('_id')
        return dic


class exerciseloglist:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        userPhone = dbToken['userPhone']
        if i.has_key('profileId') and len(i.get('profileId')) > 0 and (not i.get('profileId') == '(null)'):
            profileId = i.get('profileId')
            user = db_engine.queryUserById(profileId)
            userPhone = str(user.userPhone)
        page = 0
        pageSize = 10
        if i.has_key('page'):
            if len(i.get('page')) > 0:
                page = int(i.get('page'))
        if i.has_key('pageSize'):
            if len(i.get('pageSize')) > 0:
                pageSize = int(i.get('pageSize'))
        return simplejson.dumps(db.queryExerciseloglist(userPhone, page, pageSize))


class targetCalorieTotalCount:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        createDate = jsonDic['createDate']
        targetCalorieTotalCount = jsonDic['targetCalorieTotalCount']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        dic = {}
        dic['createDate'] = createDate
        dic['targetCalorieTotalCount'] = targetCalorieTotalCount
        dic['userPhone'] = dbToken['userPhone']
        uid = db.updateExerciseloglist(dic)
        dic['uid'] = str(uid)
        dbDic = db.findExerciseloglist(dic['uid'])
        return simplejson.dumps(dbDic)


class targetTotalMinute:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        createDate = jsonDic['createDate']
        targetTotalMinute = jsonDic['targetTotalMinute']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        tz = pytz.timezone(pytz.country_timezones('cn')[0])
        dateArray = thisWeek(datetime.datetime.fromtimestamp(createDate, tz))
        print dateArray
        for date in dateArray:
            dic = {}
            dic['createDate'] = int(az_dateutil.date2timestamp(date))
            dic['targetTotalMinute'] = targetTotalMinute
            dic['userPhone'] = dbToken['userPhone']
            db.updateExerciseloglist(dic)
        dic = {}
        dic['createDate'] = createDate
        dic['targetTotalMinute'] = targetTotalMinute
        dic['userPhone'] = dbToken['userPhone']
        uid = db.updateExerciseloglist(dic)
        dic['uid'] = str(uid)
        dbDic = db.findExerciseloglist(dic['uid'])
        return simplejson.dumps(dbDic)


def thisWeek(date=datetime.datetime.today()):
    dateArray = []
    for i in range(0, date.isoweekday()):
        dateArray.append(date-datetime.timedelta(i))
    for i in range(1, 8-date.isoweekday()):
        dateArray.append(date+datetime.timedelta(i))
    return dateArray

def thisWeekLastDayTimestamp(date=datetime.datetime.today()):
    dateArray = []
    for i in range(0, date.isoweekday()):
        dateArray.append(date-datetime.timedelta(i))
    for i in range(1, 8-date.isoweekday()):
        dateArray.append(date+datetime.timedelta(i))
    minDay = 0
    for d in dateArray:
        if az_dateutil.date2timestamp(d) > minDay:
            minDay = az_dateutil.date2timestamp(d)
    return minDay

class sporteventlist:
    def GET(self):
        setApiVersion()
        return simplejson.dumps(db.querySportEventList())


class exerciselog:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        type = jsonDic['type']
        weight = float(jsonDic['weight'])
        createDate = jsonDic['createDate']
        min = int(jsonDic['min'])
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        dic = {}
        dic['type'] = type
        dic['createDate'] = createDate
        dic['userPhone'] = dbToken['userPhone']
        dic['weight'] = weight
        sportEvent = db.querySportEventByType(type)
        if sportEvent.has_key('intensity') and sportEvent['intensity'] == 2:
            min = min*2
        dic['min'] = min
        uid = db.updateExerciseloglistByExerice(dic)
        print uid
        dic['uid'] = str(uid)
        dbDic = db.findExerciseloglist(dic['uid'])
        return simplejson.dumps(dbDic)


class questionlist:
    def GET(self, uid):
        i = web.input()
        accessToken = i.get('accessToken')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        # save log
        api_statistics.logQuestion(dbToken['userPhone'])
        return simplejson.dumps(db.queryQuestionListByTopicId(uid, dbToken['userPhone']))


class questionanswer:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        uid = jsonDic['uid']
        answers = jsonDic['answers']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        dic = {}
        dic['userPhone'] = dbToken['userPhone']
        dic['uid'] = uid
        dic['answers'] = answers
        return simplejson.dumps(db.updateUserAnswerRecord(dic))


class recorddetail:
    def GET(self, uid):
        i = web.input()
        accessToken = i.get('accessToken')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        return simplejson.dumps(db.queryQuestionRecord(uid))


class surveyresult:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = ''
        if jsonDic.has_key('accessToken'):
            accessToken = jsonDic['accessToken']
        if jsonDic.has_key('uid'):
            surveyId = jsonDic['uid']
        else:
            surveyName = jsonDic['survey']
            survey = db_engine.querySurveyByName(surveyName)
            if survey == None:
                raise web.NotFound("")
            surveyId = str(survey.id)

        surveyResult = jsonDic['surveyResult']
        if not isinstance(surveyResult, list):
            raise web.internalerror
        dbToken = db.queryUserByToken(accessToken)
        dic = {}
        dic['uid'] = surveyId
        if dbToken != None:
            dic['userPhone'] = dbToken['userPhone']
        else:
            dic['userPhone'] = ''
        dic['surveyResult'] = surveyResult
        if not db_engine.createSurveyResult(dic):
            raise web.NotFound("")
        else:
            surveyInstanceDB.updateSurveySchedule(dbToken['userPhone'], db_engine.querySurvey(dic['uid'])[0]['name'])
        return simplejson.dumps({})


class medicineCount:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        remainingMedicine = jsonDic['remainingMedicine']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        aes_cipher = aes.AESCipher(aes.aes_key)
        db_engine.updateUserRemainMedicine(aes_cipher.encrypt(remainingMedicine), dbToken['userPhone'])
        return simplejson.dumps({'remainingMedicine': remainingMedicine})

class medicineManagement:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        if jsonDic.has_key('medicines'):
            models = jsonDic['medicines']
            modelList = []
            for modelDic in models:
                modelList.append(self.createOrUpdate(modelDic, dbToken))
            return simplejson.dumps(modelList)
        else:
            return simplejson.dumps(self.createOrUpdate(jsonDic, dbToken))

    def createOrUpdate(self, jsonDic, dbToken):
        createDate = jsonDic['createDate']
        done = jsonDic['done']
        dic = {}
        dic['done'] = str(done)
        dic['createDate'] = createDate
        dic['userPhone'] = dbToken['userPhone']
        result = db_engine.createMedicineFix(dic)
        dic['uid'] = str(result[0])
        dic.pop('userPhone')
        if dic.has_key('_id'):
            dic.pop('_id')
        aes_cipher = aes.AESCipher(aes.aes_key)
        #更新剩余药片数量，如果变化，则更新
        remainingMedicine = int(aes_cipher.decrypt(db_engine.queryUser(dbToken['userPhone']).remainingMedicine))
        if int(done) == 1 and result[1]:
            remainingMedicine -= 1
            if remainingMedicine < 0:
                remainingMedicine = 0
            db_engine.updateUserRemainMedicine(aes_cipher.encrypt(remainingMedicine), dbToken['userPhone'])
        elif int(done) == 0 and result[1]:
            remainingMedicine += 1
            db_engine.updateUserRemainMedicine(aes_cipher.encrypt(remainingMedicine), dbToken['userPhone'])
        dic['remainingMedicine'] = remainingMedicine
        setApiVersion()
        return dic

    # def DELETE(self):
    #     i = web.data()
    #     jsonDic = {}
    #     deleteById = True
    #     if i == '':
    #         print 'empty i'
    #         i = web.input()
    #         jsonDic['accessToken'] = i.get("accessToken")
    #         if i.has_key('uid'):
    #             jsonDic['uid'] = i.get('uid')
    #         if i.has_key('createDate'):
    #             jsonDic['createDate'] = i.get('createDate')
    #             deleteById = False
    #     else:
    #         jsonDic = eval(i)
    #     accessToken = jsonDic['accessToken']
    #     dbToken = db.queryUserByToken(accessToken)
    #     if dbToken == None:
    #         raise web.unauthorized
    #     if deleteById:
    #         uid = jsonDic['uid']
    #     else:
    #         uid = db_engine.queryMedicineByCreateDate(jsonDic['createDate'], dbToken['userPhone'])
    #     #
    #     db_engine.deleteMedicine(uid)
    #     remainingMedicine = db_engine.queryUser(dbToken['userPhone']).remainingMedicine
    #     remainingMedicine += 1
    #     db_engine.updateUserRemainMedicine(remainingMedicine, dbToken['userPhone'])
    #     setApiVersion()
    #     return simplejson.dumps({})


class medicineList:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        userPhone = dbToken['userPhone']
        if i.has_key('profileId') and len(i.get('profileId')) > 0 and (not i.get('profileId') == '(null)'):
            profileId = i.get('profileId')
            user = db_engine.queryUserById(profileId)
            userPhone = str(user.userPhone)
        page = 0
        pageSize = 10
        done = 1
        if i.has_key('page'):
            if len(i.get('page')) > 0:
                page = int(i.get('page'))
        if i.has_key('pageSize'):
            if len(i.get('pageSize')) > 0:
                pageSize = int(i.get('pageSize'))
        if i.has_key('done'):
            if len(i.get('done')) > 0:
                done = int(i.get('done'))
        bpDic = db_engine.queryMedicineListByParam(userPhone, page, pageSize, done)
        setApiVersion()
        return simplejson.dumps(bpDic)


class userList:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        page = 0
        pageSize = 10
        done = 1
        if i.has_key('page'):
            if len(i.get('page')) > 0:
                page = int(i.get('page'))
        if i.has_key('pageSize'):
            if len(i.get('pageSize')) > 0:
                pageSize = int(i.get('pageSize'))
        userDic = db_engine.queryUserListByParam(page, pageSize)
        setApiVersion()
        return simplejson.dumps(userDic)


class patientadd:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        inviteCode = jsonDic['inviteCode']
        if not len(str(inviteCode)) == 6:
            raise web.NotFound("")
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        caregivers = db_engine.queryCaregiverByPhoneAndInviteCode(dbToken['userPhone'], inviteCode)
        if caregivers.count() == 0:
            raise web.NotFound("")
        caregiver = caregivers[0]
        db_engine.updateCaregiverByInviteCode(str(caregiver.id))
        userDic = {}
        user = db_engine.queryUser(caregiver.caredUserPhone)
        userDic['uid'] = str(user.id)
        userDic['nickName'] = user.nickName
        #
        bmiDic = db.queryBmiList(user.userPhone, 0, 1)
        if len(bmiDic['bmis']) == 0:
            userDic['bmiIndex'] = 0.0
        else:
            userDic['bmiIndex'] = bmiDic['bmis'][0]['bmiIndex']
        #
        medicineDic = db_engine.queryMedicineListByParam(user.userPhone, 0, 1, 0)
        if len(medicineDic['medicines']) == 0:
            userDic['takingDays'] = 0
        else:
            userDic['takingDays'] = medicineDic['medicines'][0]['remainingMedicine']
        #
        exericeLogDic = db.queryExerciseloglist(user.userPhone, 0, 1)
        if len(exericeLogDic['exericelogs']) == 0:
            userDic['consumeHeatCount'] = 0.0
            userDic['totalMin'] = 0.0
        else:
            totalMin = 0
            for log in exericeLogDic['exericelogs']:
                totalMin += log['totalMinute']
            userDic['consumeHeatCount'] = 0
            userDic['totalMin'] = totalMin
        return simplejson.dumps(userDic)


# class list:
#     def GET(self):
#         setApiVersion()
#         return simplejson.dumps({'test': 'test'})


class article:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        title = jsonDic['title']
        topicId = jsonDic['topicId']
        des = jsonDic['des']
        image = jsonDic['image']
        article = topic.Article(title=title, topicId=topicId, des=des, image=image,
                                artileCatalog=jsonDic['articleCatagary'], articleIndex=jsonDic['articleIndex'])
        article.content = topic.articleHtml %(article.title, '', '', article.image, article.des, article.source)
        connect('az', host=db_engine.host)
        article.save()
        setApiVersion()
        return simplejson.dumps({})


class question:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        title = jsonDic['title']
        topicId = jsonDic['topicId']
        correctAnswer = jsonDic['correctAnswer']
        choices = jsonDic['choices']
        question = topic.Question(title=title, topicId=topicId, correctAnswer=correctAnswer, choices=choices,
                                  articleIndex=jsonDic['articleIndex'])
        connect('az', host=db_engine.host)
        question.save()
        setApiVersion()
        return simplejson.dumps({})


class t:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        title = jsonDic['title']
        des = jsonDic['des']
        image = jsonDic['image']
        t = topic.Topic(title=title, des=des, image=image)
        connect('az', host=db_engine.host)
        t.save()
        setApiVersion()
        return simplejson.dumps({})


class logout:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        db_engine.deleteToken(accessToken)


class unreadArticleCount:
    def GET(self):
        i = web.input()
        accessToken = i.get('accessToken')
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        count = db.queryUnReadArticleCount(dbToken['userPhone'])
        setApiVersion()
        return simplejson.dumps({"unreadArticleCount": count})


class deleteExerice:
    def DELETE(self):
        i = web.data()
        jsonDic = {}
        if i == '':
            print 'empty i'
            i = web.input()
            jsonDic['accessToken'] = i.get("accessToken")
            if i.has_key('uid'):
                jsonDic['uid'] = i.get('uid')
        else:
            jsonDic = eval(i)
        accessToken = jsonDic['accessToken']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            raise web.unauthorized
        db.deleteExerice(jsonDic['uid'])
        setApiVersion()
        return simplejson.dumps({})


class admin_login:
    def POST(self):
        i = web.input()
        userPhone = i['userPhone']
        userPwd = i['userPwd']
        user = db.query(userPhone)
        if user == None:
            raise web.NotFound("")
        elif user['userPwd'] != hashlib.md5(userPwd).hexdigest().upper():
            raise web.unauthorized
        web.header('content-type', 'application/json')
        accessToken = random_str()
        db.createToken({'accessToken': accessToken, 'userPhone': userPhone})
        setApiVersion()
        web.header('content-type', 'text/html')
        web.setcookie('accessToken', accessToken, 3600)
        return web.seeother('/static/admin_form.html')


class admin_survey_schedule:
    def GET(self):
        i = web.input()
        i['accessToken'] = web.cookies().get("accessToken")
        if not i.has_key("accessToken"):
            web.header('content-type', 'text/html')
            return web.redirect("/survey/admin")
        accessToken = i['accessToken']
        dbToken = db.queryUserByToken(accessToken)
        if dbToken == None:
            web.header('content-type', 'text/html')
            return web.redirect("/static/login.html")
        web.header('content-type', 'application/json')
        setApiVersion()
        surveySchedule = surveyInstanceDB.querySurveySchedule(dbToken['userPhone'])
        dic = {}
        aes_cipher = aes.AESCipher(aes.aes_key)
        user = db_engine.queryUser(surveySchedule.userPhone)
        dic['userPhone'] = surveySchedule.userPhone
        dic['userPhoneCreateDate'] = time.strftime('%m/%d/%Y %H:%M', time.localtime(user.createDate))
        dic['lastSurvey'] = aes_cipher.decrypt(surveySchedule.lastSurvey)
        dic['uid'] = str(surveySchedule.id)
        dic['currentSurvey'] = aes_cipher.decrypt(surveySchedule.currentSurvey)
        dic['nextSurvey'] = aes_cipher.decrypt(surveySchedule.nextSurvey)
        dic['firstDone'] = time.strftime('%m/%d/%Y %H:%M', time.localtime(surveySchedule.firstDone))
        dic['lastDone'] = time.strftime('%m/%d/%Y %H:%M', time.localtime(surveySchedule.lastDone))
        return simplejson.dumps(dic)

    def POST(self):
        i = web.input()
        userPhone = i['userPhone']
        firstDone = i['firstDone']
        lastDone = i['lastDone']
        surveyInstanceDB.updateSurveyScheduleByFirstDone(userPhone, firstDone, lastDone)
        setApiVersion()
        return simplejson.dumps({})


class admin_survey_schedule_check:
    def GET(self):
        surveyInstanceDB.checkSurveySchedule()
        setApiVersion()
        return simplejson.dumps({})


class admin_remove_user:
    def POST(self):
        i = web.data()
        jsonDic = eval(i)
        userPhone = jsonDic['userPhone']
        userPwd = jsonDic['userPwd']
        salt = jsonDic['salt']
        user = db.query(userPhone)
        if user == None:
            raise web.NotFound("")
        elif user['userPwd'] != hashlib.md5(userPwd).hexdigest().upper():
            raise web.unauthorized
        elif salt != '000000':
            raise web.unauthorized
        removeUser(userPhone)
        setApiVersion()
        return simplejson.dumps({})


def removeUser(userPhone):
    connect('az', host=db_engine.host)
    print db_engine.User.objects(userPhone=userPhone).delete()
    print db_engine.Token.objects(userPhone=userPhone).delete()
    print db_engine.ValidateCode.objects(userPhone=userPhone).delete()
    print surveyInstanceDB.SurveySmsLog.objects(userPhone=userPhone).delete()
    print surveyInstanceDB.SurveySchedule.objects(userPhone=userPhone).delete()
    print surveyInstanceDB.SurveyLog.objects(userPhone=userPhone).delete()
    print db_engine.SurveyResult.objects(userPhone=userPhone).delete()
    print topic.ArticleStatus.objects(userPhone=userPhone).delete()

    conn = db.pymongo.mongo_client.MongoClient(db_engine.host, port=27017)
    database = conn.az
    smokeC = database.smoke
    questionRecordC = database.questionRecord
    medicineC = database.medicine
    exericelogC = database.exericelog
    cholesterolC = database.cholesterol
    caregiverC = database.caregiver
    bpC = database.bp
    bmiC = database.bmi

    print smokeC.remove({'userPhone': userPhone})
    print questionRecordC.remove({'userPhone': userPhone})
    print medicineC.remove({'userPhone': userPhone})
    print exericelogC.remove({'userPhone': userPhone})
    print cholesterolC.remove({'userPhone': userPhone})
    print caregiverC.remove({'userPhone': userPhone})
    print caregiverC.remove({'caredUserPhone': userPhone})
    print bpC.remove({'userPhone': userPhone})
    print bmiC.remove({'userPhone': userPhone})


app = web.application(urls, globals())


def setApiVersion():
    print web.ctx.env.get('HTTP_USER_AGENT', 'ios')
    web.header('Access-Control-Allow-Origin', '*')
    web.header("api-version", "v 0.55")

# app = web.application(urls, globals()).wsgifunc()
#
# application = sae.create_wsgi_app(app)

if __name__ == "__main__":
    app.run()